<template>
  <div class="add" @click="dialogVisible = true">
    <img src="@/assets/svg/add.svg" alt="" />
  </div>

  <!-- 添加好友对话框 -->
  <el-dialog
    class="dialog"
    v-model="dialogVisible"
    title="添加好友"
    width="35%"
    draggable
    :before-close="handleClose"
  >
    <!-- 查询表单 -->
    <el-row>
      <el-col :span="5" class="text">选择角色</el-col>
      <el-col :span="18">
        <el-radio-group v-model="search_role">
          <el-radio :label="0" border v-show="userInfo.role!==2">管理员</el-radio>
          <el-radio :label="1" border>教师</el-radio>
          <el-radio :label="2" border>学生</el-radio>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="5" class="text">查询方式</el-col>
      <el-col :span="12">
        <el-radio-group v-model="search_mode">
          <el-radio label="a" border v-show="search_role!==2" >编号</el-radio>
          <el-radio label="b" border>手机号码</el-radio>
          <el-radio label="c" border v-show="search_role===2">学号</el-radio>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="5" class="text">你的输入</el-col>
      <el-col :span="12">
        <el-input 
          v-model="input" 
          placeholder="请输入内容查询用户" 
          class="input-with-select" 
          @keydown.enter="search"
          size="large"
          >
          <template #append>
            <el-button :icon="Search" @click="search"/>
          </template>
        </el-input>
      </el-col>
    </el-row>

    <!-- 好友信息 -->
    <div class="friend" v-show="friendInfo?.id">
      <div class="avatar">
        <el-avatar class="img" :icon="UserFilled" :src="friendInfo?.avatar" shape="square" alt="" />
      </div>
      <div class="info">
        <span class="name">
          {{friendInfo?.name}}
          <el-icon class="icon" :class="friendInfo?.gender==='男' ? 'blue': 'red'"><Avatar /></el-icon>
        </span>
        <span v-if="friendInfo?.role!==2">编号：{{friendInfo?.identify}}</span>
        <span v-if="friendInfo?.role===2">学号：{{friendInfo?.stu_num}}</span>
        <span v-if="friendInfo?.role!==0">学院：{{friendInfo?.college}}</span>
        <span v-if="friendInfo?.role===0">手机：{{friendInfo?.phone}}</span>
        <span v-if="friendInfo?.role!==2">邮箱：{{friendInfo?.email}}</span>
        <span v-if="friendInfo?.role===2">班级：{{friendInfo?.class}}</span>
      </div>
    </div>
    <div class="apply" v-if="friendInfo.id">
      <el-link class="link" type="primary" underline @click="applyIsShow=!applyIsShow">点击发送消息</el-link>
      <el-input type="textarea" v-show="applyIsShow" v-model.trim="applyText" clearable/>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button color="#07c160" v-show="applyIsShow" @click="send">
          确认发送
          <el-icon style="padding-left:5px;"><Promotion /></el-icon>
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { Search, UserFilled, Avatar, Promotion } from '@element-plus/icons-vue';
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { binMsg } from '@/global/api.js';
import { getUserByIdentify, getUserByPhone } from '@/services/roleCommon.js'
import { getStuByStuNum } from '@/services/student.js'
import { addFriend } from '@/services/friend.js'

const store = useStore()
const router = useRouter()
const userInfo = computed(()=>store.state.userModule.userInfo) // 当前用户信息
const dialogVisible = ref(false) // 对话框的显示隐藏
const input = ref('') // 输入的内容
const friendInfo = ref({}) // 好友信息
const applyIsShow = ref(false) // 添加好友的展示
const applyText = ref(`你好，我是${userInfo.value.name}~`) // 添加好友时发送的消息
const search_role = ref('') // 查询角色
const search_mode = ref('') // 查询方式

// 查找好友
const search = async () => {
  binMsg().closeAll()
  if (search_role.value === '') return binMsg('warning', '请选择角色')
  if (search_mode.value === '') return binMsg('warning', '请选择查询方式')
  if (input.value === '') return binMsg('warning', '请输入内容')
  // console.log(search_role.value, search_mode.value, input.value);
  let findResult = null
  // 查询学生
  if (search_role.value === 2) {
    // 根据手机号查询
    if (search_mode.value === 'b') {
      const { data: res } = await getUserByPhone(search_role.value, input.value)
      findResult = res
    } else {
      // 根据学号查询
      const { data: res } = await getStuByStuNum(input.value)
      findResult = res
    }
  } else {
    // 查询管理员或教师
    if (search_mode.value === 'a') {
      // 根据编号查询
      const { data: res } = await getUserByIdentify(search_role.value, input.value)
      findResult = res
    } else {
      // 根据手机号查询
      const { data: res } = await getUserByPhone(search_role.value, input.value)
      findResult = res
    }
  }
  if (findResult.meta.status === 400) return binMsg('error', findResult.meta.msg)
  friendInfo.value = findResult.data.data
}

// 发送添加好友消息
const send = async () => {
  binMsg().closeAll()
  if (!friendInfo.value.id) return binMsg('warning', '请先查询用户')
  if (friendInfo.value.id === userInfo.value.id) return binMsg('info', '不能给自己发消息哦~')
  if (!applyText.value) return binMsg('warning', '请输入申请消息')
  // 先添加好友，判断是否好友已在会话列表
  const { data: res } = await addFriend({
    uid: userInfo.value.id,
    fid: friendInfo.value.id,
    urole: userInfo.value.role,
    frole: friendInfo.value.role
  })
  // 说明好友已在会话中
  if (res.meta.status !== 200) {
    binMsg('warning', res.meta.msg)
    router.push({
      path: `/home/message/chat/${friendInfo.value.id}`,
      query: {
        role: friendInfo.value.role
      }
    })
    handleClose()
    return
  }
  // 封装好消息数据
  let msgData = {
    uid: userInfo.value.id,
    fid: friendInfo.value.id,
    urole: userInfo.value.role,
    content: applyText.value,
    time: Date.now(),
    state: false
  }
  // 将消息存入数据库
  store.dispatch('messageModule/insertMsg', msgData)
  binMsg('success', res.meta.msg)
  // 跳转到对应好友聊天框
  router.push({
    path: `/home/message/chat/${friendInfo.value.id}`,
    query: {
      role: friendInfo.value.role
    }
  })
  // 重新更新好友列表
  store.dispatch('friendModule/initFriendList', { id: userInfo.value.id })
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  input.value = ''
  friendInfo.value = ''
  search_mode.value = ''
  search_role.value = ''
  applyIsShow.value = false
  applyText.value = `你好，我是${userInfo.value.name}~`
}

// 切换角色时，重新选择查询方式
watch(() => search_role.value, () => {
  search_mode.value = ''
})

</script>

<style lang="less" scoped>
.add {
  background-color: #e2e2e2;
  height: 26px;
  width: 26px;
  line-height: 25px;
  text-align: center;
  border-radius: 4px;
  margin-top: 3px;
  user-select: none;
  img {
    width: 15px;
    height: 100%;
  }
}
.add:hover {
  cursor: pointer;
  background-color: #d1d1d1;
}

.text {
  font-size: 16px;
  color: #303133;
  letter-spacing: 1px;
}

.friend {
  width: 100%;
  padding: 30px 0;
  display: flex;
  // border-bottom: 1px solid #f3f3f3;
  .avatar {
    width: 65px;
    height: 65px;
    padding: 7px 20px 0 15px;
    .img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    display: flex;
    flex-direction: column;
    span {
      display: inline-block;
      height: 30px;
      line-height: 30px;
    }
    .name {
      color: black;
      font-size: 16px;
      align-items: center;
      vertical-align: middle;
      .icon {
        padding: 0 2px;
      }
      .blue {
        color: #10b1ff;
      }
      .red {
        color: #f37e7d;
      }
    }
  }
}

.apply {
  margin: -35px 0 0 100px;
  .link {
    user-select: none;
    height: 20px;
  }
}

/deep/ .el-dialog.el-dialog--center {
  border-radius: 8px !important;
}

/deep/ .el-dialog__body {
  border-radius: 8px !important;
}

/deep/#el-id-81-13 {
  padding-top: 10px !important;
}

</style>
